import React, { useState, useEffect } from 'react';
import { 
  Table, Button, Modal, Form, Input, Select, Space, message, Popconfirm, 
  Typography, Card, Switch, Divider 
} from 'antd';
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import { stockInfoApi } from '../../api';

const { Title } = Typography;
const { Option } = Select;

const StockInfo = () => {
  const [stockList, setStockList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingStock, setEditingStock] = useState(null);
  const [form] = Form.useForm();

  // 获取所有股票信息
  const fetchStockInfo = async () => {
    setLoading(true);
    try {
      const data = await stockInfoApi.getAllStockInfo();
      setStockList(data);
    } catch (error) {
      message.error('获取股票信息失败');
      console.error('获取股票信息失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 初始化股票信息
  const initializeStockInfo = async () => {
    try {
      await stockInfoApi.initializeStockInfo();
      message.success('股票信息初始化成功');
      fetchStockInfo();
    } catch (error) {
      message.error('初始化股票信息失败');
      console.error('初始化股票信息失败:', error);
    }
  };

  // 添加或更新股票信息
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      // 确保类型是数字
      values.type = parseInt(values.type, 10);
      
      if (editingStock) {
        // 更新
        await stockInfoApi.updateStockInfo(editingStock.code, values);
        message.success('股票信息更新成功');
      } else {
        // 添加
        await stockInfoApi.addStockInfo(values);
        message.success('股票信息添加成功');
      }
      
      setModalVisible(false);
      form.resetFields();
      setEditingStock(null);
      fetchStockInfo();
    } catch (error) {
      console.error('保存股票信息失败:', error);
      message.error('保存股票信息失败');
    }
  };

  // 删除股票信息
  const handleDelete = async (code) => {
    try {
      await stockInfoApi.deleteStockInfo(code);
      message.success('股票信息删除成功');
      fetchStockInfo();
    } catch (error) {
      message.error('删除股票信息失败');
      console.error('删除股票信息失败:', error);
    }
  };

  // 编辑股票信息
  const handleEdit = (record) => {
    setEditingStock(record);
    form.setFieldsValue({
      code: record.code,
      name: record.name,
      type: record.type.toString(),
      can_trade: record.can_trade === "1" ? "1" : "0"
    });
    setModalVisible(true);
  };

  // 添加新股票
  const handleAdd = () => {
    setEditingStock(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 初始加载
  useEffect(() => {
    fetchStockInfo();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: '代码',
      dataIndex: 'code',
      key: 'code',
      sorter: (a, b) => a.code.localeCompare(b.code)
    },
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      sorter: (a, b) => a.name.localeCompare(b.name)
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => type === 1 ? '指数' : '行业',
      filters: [
        { text: '指数', value: 1 },
        { text: '行业', value: 2 }
      ],
      onFilter: (value, record) => record.type === value
    },
    {
      title: '可交易',
      dataIndex: 'can_trade',
      key: 'can_trade',
      render: (can_trade) => can_trade === "1" ? '是' : '否',
      filters: [
        { text: '是', value: "1" },
        { text: '否', value: "0" }
      ],
      onFilter: (value, record) => record.can_trade === value
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm
            title="确定要删除这个股票信息吗?"
            onConfirm={() => handleDelete(record.code)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger>删除</Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div style={{ padding: '20px' }}>
      <Card>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <Title level={4}>股票信息管理</Title>
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />} 
              onClick={handleAdd}
            >
              添加股票
            </Button>
            <Button 
              icon={<ReloadOutlined />} 
              onClick={fetchStockInfo}
            >
              刷新
            </Button>
            <Popconfirm
              title="确定要初始化股票信息吗? 这将覆盖现有数据。"
              onConfirm={initializeStockInfo}
              okText="确定"
              cancelText="取消"
            >
              <Button>初始化数据</Button>
            </Popconfirm>
          </Space>
        </div>
        
        <Divider />
        
        <Table
          columns={columns}
          dataSource={stockList}
          rowKey="code"
          loading={loading}
          size='middle'
          pagination={false}
        />
      </Card>

      {/* 添加/编辑股票的表单弹窗 */}
      <Modal
        title={editingStock ? '编辑股票信息' : '添加股票信息'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        maskClosable={true}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="code"
            label="股票代码"
            rules={[
              { required: true, message: '请输入股票代码' },
              { pattern: /^[0-9]+\.[A-Z]+$/, message: '股票代码格式应为: 数字.交易所代码' }
            ]}
            disabled={!!editingStock}
          >
            <Input placeholder="例如: 000300.XSHG" disabled={!!editingStock} />
          </Form.Item>
          
          <Form.Item
            name="name"
            label="股票名称"
            rules={[{ required: true, message: '请输入股票名称' }]}
          >
            <Input placeholder="例如: 沪深300" />
          </Form.Item>
          
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true, message: '请选择类型' }]}
          >
            <Select placeholder="请选择类型">
              <Option value="1">指数</Option>
              <Option value="2">行业</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            name="can_trade"
            label="可交易"
            rules={[{ required: true, message: '请选择是否可交易' }]}
          >
            <Select placeholder="请选择是否可交易">
              <Option value="1">是</Option>
              <Option value="0">否</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default StockInfo; 